<?php

namespace zhtfrontend\modules\teachergrowth\controllers;

use common\components\helpers\Fun;
use common\models\datas\Cate;
use common\models\datas\Category;
use common\models\datas\Customer;
use common\models\datas\Student;
use doumiaoduo\aliyun\OssuploaderHelper;
use yii\console\Exception;
use yii\data\ActiveDataProvider;
use yii\db\Query;
use yii\web\UploadedFile;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassManageAttribute;
use zhtfrontend\models\datas\ClassManageGoods;
use zhtfrontend\models\datas\ClassManageTeacher;
use zhtfrontend\models\datas\ClassManageTime;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\LessonStudents;
use zhtfrontend\models\datas\Mechanic;
use zhtfrontend\models\datas\OrdersItems;
use zhtfrontend\models\datas\StudentCheck;
use zhtfrontend\models\datas\Teacher;
use zhtfrontend\modules\teachergrowth\components\rest\ActiveController;
use yii\helpers\ArrayHelper;
use yii\web\ForbiddenHttpException;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;

class StudentmanageController extends ActiveController

{
    private $_config;
    public $modelClass = 'zhtfrontend\models\datas\ClassManage';

    public $serializer = [
        'class' => 'zhtfrontend\modules\teachergrowth\components\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create'], $actions['update'], $actions['delete'], $actions['view']);
        return $actions;
    }

    //下面是首页
    public function actionManagelist()
    {
        $data = \Yii::$app->request->post();
        $role = ArrayHelper::keyExists('role', $data) ? $data['role'] : '';
        $user_id = ArrayHelper::keyExists('user_id', $data) ? $data['user_id'] : '';
        $teacher_id = ArrayHelper::keyExists('teacher_id', $data) ? $data['teacher_id'] : '';
        if ($role == "teache_teacher") {
            $Teacher_array = Teacher::find()->select('id')->where(['id' => $teacher_id])->column();
        } else {
            $mechanic = Mechanic::find()->select('id')->where(['admin_id' => $user_id])->column();
            $Teacher_array = Teacher::find()->select('id')->where(['mechanic_id' => $mechanic])->column();
        }
        $class_manage_teacher = ClassManageTeacher::find()->where(['teacher_id' => $Teacher_array])->asArray()->all();

        if (empty($class_manage_teacher)) {
            return ['statusCode' => 0, 'message' => 'error', 'result' => '没有课程'];
        } else {
            $class_ids = ArrayHelper::getColumn($class_manage_teacher, 'class_id');
            $class_manage_begins = ClassManage::find()->where(['class_id' => $class_ids, 'status' => [1, 2]])->asArray()->all();//已经开课
            $class_manage_appoint = ClassManage::find()->where(['class_id' => $class_ids])->asArray()->all();//已经开课，未开课，结束

            //下面查找开课学员，就是这节课已经开课并且学员已经办理入学（已经支付）
            $orders_begins_all = 0;
            $orders_appoint_all = 0;
            $goods_id_array = $class_idss = [];
            foreach ($class_manage_begins as $key => $val) {
                $class_idss[] = $val['class_id'];
            }
            $goods_id_array = (new Query())->select('goods_id')->from('{{%class_manage_goods}}')->where(['in', 'class_id', $class_idss])->column(Fun::getSiteDb());
            $orders_begins = (new Query())->select("*")->from('{{%orders_items}} oi')
                ->leftJoin('{{%orders}} or', 'oi.orders_id=or.id')
                ->where(['or.status' => [1, 5, 6, 7], 'or.pay_status' => [1]])
                ->andWhere(['in', 'oi.goods_id', $goods_id_array])->all(Fun::getSiteDb());
            $orders_begins_all = $orders_begins_all + count($orders_begins);

            //下面查找，约课的学员，就是这节课为交钱（未支付）
            $goods_id_arraya = $class_idsa = [];
            foreach ($class_manage_appoint as $key => $val) {
                $class_idsa[] = $val['class_id'];
            }
            $goods_id_arraya = (new Query())->select('goods_id')->from('{{%class_manage_goods}}')->where(['in', 'class_id', $class_idsa])->column(Fun::getSiteDb());
            $orders_appoint = (new Query())->select("*")->from('{{%orders_items}} oi')
                ->leftJoin('{{%orders}} or', 'oi.orders_id=or.id')
                ->where(['or.status' => [0, 1], 'or.pay_status' => [0]])
                ->andWhere(['in', 'oi.goods_id', $goods_id_arraya])->all(Fun::getSiteDb());
            $orders_appoint_all = $orders_appoint_all + count($orders_appoint);
            $items = [
                'orders_begins' => $orders_begins_all,
                'orders_appoint' => $orders_appoint_all
            ];
            return ['statusCode' => 200, 'message' => 'error', 'items' => $items];
        }
    }


    //查找出开课学员的列表来
    public function actionManageopen()
    {
        $data = \Yii::$app->request->post();
        $role = ArrayHelper::keyExists('role', $data) ? $data['role'] : '';
        $user_id = ArrayHelper::keyExists('user_id', $data) ? $data['user_id'] : '';
        $teacher_id = ArrayHelper::keyExists('teacher_id', $data) ? $data['teacher_id'] : '';
        $week = ArrayHelper::keyExists('week', $data) ? $data['week'] : '全部'; //下面是周几
        $types = ArrayHelper::keyExists('types', $data) ? $data['types'] : '全部';//下面是上课类型
        $category = ArrayHelper::keyExists('category', $data) ? $data['category'] : '全部';//下面是课程分类
        $course = ArrayHelper::keyExists('course', $data) ? $data['course'] : '';//下面是课程名称
        if ($role == "teache_teacher") {
            $Teacher_array = Teacher::find()->select('id')->where(['id' => $teacher_id])->column();
        } else {
            $mechanic = Mechanic::find()->select('id')->where(['admin_id' => $user_id])->column();
            $Teacher_array = Teacher::find()->select('id')->where(['mechanic_id' => $mechanic])->column();
        }

        $class_manage_query = (new Query())->select('
        cm.class_id as class_id,cm.start_time as start_time,cma.course as course_name,cmg.goods_id as goods_id,
        cmt.class_day as course_week,cmt.start_time as course_begin,cmt.end_time as course_end
        ')->from('{{%class_manage}} cm')
            ->leftJoin('{{%class_manage_teacher}} cmtt', 'cmtt.class_id=cm.class_id')
            ->leftJoin('{{%class_manage_time}} cmt', 'cm.class_id=cmt.class_id')
            ->leftJoin('{{%class_manage_goods}} cmg', 'cmg.class_id=cm.class_id')
            ->leftJoin('{{%class_manage_attribute}} cma', 'cma.class_id=cm.class_id')
            //->leftJoin('{{%class_student}} cs', 'cs.class_manage_id=cm.class_id')
            ->where(['in', 'cmtt.teacher_id', $Teacher_array])->andWhere(['cm.status' => 1]);
        //分类筛选
        if (isset($category) && $category != '全部') {
            $cate = (new Query())->select('*')->from('{{%cate}}')->where(['id' => $category])->one();
            $cate_ids = explode(',', $cate['arrchild_id']);
            $classs_ids = (new Query())->select('cmg.class_id')->from('{{%goods}} g')
                ->leftJoin('{{%class_manage_goods}} cmg', 'g.id=cmg.goods_id')
                ->where(['in', 'g.cat_id', $cate_ids])->column(Fun::getSiteDb());
            $class_manage_query->andWhere(['in', 'cm.class_id', $classs_ids]);
        }

        //日期筛选
        if (isset($week) && $week !== '全部') {
            $class_manage_query->andWhere(['cmt.class_day' => $week]);
        }
        //授课形式筛选
        if (isset($types) && $types !== '全部') {
            $class_manage_query->andWhere(['cma.teacher_form' => $types]);
        }
        //课程名称筛选
        if (isset($course) && !empty($course)) {
            $class_manage_query->andWhere(['cma.course' => $course]);
        }
        $class_manage_data = $class_manage_query->all(Fun::getSiteDb());
        $goods_info_array = [];
        if (empty($class_manage_data)) {
            return ['statusCode' => 0, 'message' => 'error', 'result' => '没有课程'];
        } else {
            foreach ($class_manage_data as $key => $val) {
                $good_data = (new Query())->select('*')->from('{{%goods}}')->where(['id' => $val['goods_id']])->one(Fun::getSiteDb());
                $cate_data = (new Query())->select('*')->from('{{%cate}}')->where(['id' => $good_data['cat_id']])->one();
                $goods_info_array[$val['class_id']] = [
                    'date' => date("Y-m", $val['start_time']),
                    'classify' => $cate_data['name'],
                    'courseName' => isset($val['course_name']) ? $val['course_name'] : '',
                    'courseWeek' => isset($val['course_week']) ? $val['course_week'] : '',
                    'courseBegin' => isset($val['course_begin']) ? $val['course_begin'] : '',
                    'courseEnd' => isset($val['course_end']) ? $val['course_end'] : '',
                    'list' => $this->getOpenlists($val['class_id']),
                ];
            }

        }
        $cate=(new Query())->select('id,name')->from('{{%cate}}')->where(['parent_id'=>0])->all();
        $items=[
            'goods_info_array'=>$goods_info_array,
            'cate'=>$cate
        ];
        //查找一下课程分类的信息
        return ['statusCode' => 200, 'message' => 'error', 'items' => $items];
    }

    //开班学员列表
    private function getOpenlists($class_id)
    {
        $list = [];
        $student_ids = (new Query())->select('student_id')->from('{{%class_student}}')->where(['class_manage_id' => $class_id])->column(Fun::getSiteDb());
        $student = (new Query())->select('*')->from('{{%student}}')->where(['in', 'id', $student_ids])->all();
        if (!empty($student)) {
            foreach ($student as $k => $v) {
                $customer = (new Query())->select('*')->from('{{%customer}}')->where(['id' => $v['customer_id']])->one();
                if ($v['sex'] == 0) { //如果是女的话
                    $sexiconBox = "dmd-female-icon";
                    $sexicon = 'icon-female';
                } else {
                    $sexiconBox = "dmd-male-icon";
                    $sexicon = 'icon-male';
                }
                if (isset($customer['mobile']) && !empty($customer['mobile'])) {
                    $callOrNot = 'dmd-call-box';
                    $call = '拨打';
                } else {
                    $callOrNot = 'dmd-call-not-box';
                    $call = '';
                }
                $list[] = [
                    'img' => isset($v['img']) ? $v['img'] : '../../images/order-count-img-no-have.jpg',
                    'sexiconBox' => $sexiconBox,
                    'sexIcon' => $sexicon,
                    'name' => isset($v['name']) ? $v['name'] : '',
                    'telephone' => isset($customer['mobile']) ? $customer['mobile'] : '暂无联系方式',
                    'callOrNot' => $callOrNot,
                    'call' => $call,
                ];
            }
        }
        return $list;
    }


    public function actionManageappoint()
    {
        $data = \Yii::$app->request->post();
        $role = ArrayHelper::keyExists('role', $data) ? $data['role'] : '';
        $user_id = ArrayHelper::keyExists('user_id', $data) ? $data['user_id'] : '';
        $teacher_id = ArrayHelper::keyExists('teacher_id', $data) ? $data['teacher_id'] : '';
        $week = ArrayHelper::keyExists('week', $data) ? $data['week'] : '全部';
        $types = ArrayHelper::keyExists('types', $data) ? $data['types'] : '全部';//下面是上课类型
        $category = ArrayHelper::keyExists('category', $data) ? $data['category'] : '全部';//下面是课程分类
        $course = ArrayHelper::keyExists('course', $data) ? $data['course'] : '';//下面是课程分类

        if ($role == "teache_teacher") {
            $Teacher_array = Teacher::find()->select('id')->where(['id' => $teacher_id])->column();
        } else {
            $mechanic = Mechanic::find()->select('id')->where(['admin_id' => $user_id])->column();
            $Teacher_array = Teacher::find()->select('id')->where(['mechanic_id' => $mechanic])->column();
        }
        $class_manage_query = (new Query())->select('
        cm.class_id as class_id,cm.start_time as start_time,cma.course as course_name,cmg.goods_id as goods_id,
        cmt.class_day as course_week,cmt.start_time as course_begin,cmt.end_time as course_end
        ')->from('{{%class_manage}} cm')
            ->leftJoin('{{%class_manage_teacher}} cmtt', 'cmtt.class_id=cm.class_id')
            ->leftJoin('{{%class_manage_time}} cmt', 'cm.class_id=cmt.class_id')
            ->leftJoin('{{%class_manage_goods}} cmg', 'cmg.class_id=cm.class_id')
            ->leftJoin('{{%class_manage_attribute}} cma', 'cma.class_id=cm.class_id')
            ->where(['in', 'cmtt.teacher_id', $Teacher_array])->andWhere(['in', 'cm.status', [0, 1]]);
        //分类筛选
        if (isset($category) && $category != '全部') {
            $cate = (new Query())->select('*')->from('{{%cate}}')->where(['id' => $category])->one();
            $cate_ids = explode(',', $cate['arrchild_id']);
            $classs_ids = (new Query())->select('cmg.class_id')->from('{{%goods}} g')
                ->leftJoin('{{%class_manage_goods}} cmg', 'g.id=cmg.goods_id')
                ->where(['in', 'g.cat_id', $cate_ids])->column(Fun::getSiteDb());
            $class_manage_query->andWhere(['in', 'cm.class_id', $classs_ids]);
        }
        //日期筛选
        if (isset($week) && $week != '全部') {
            $class_manage_query->andWhere(['cmt.class_day' => $week]);
        }
        //授课形式筛选
        if (isset($types) && $types != '全部') {
            $class_manage_query->andWhere(['cma.teacher_form' => $types]);
        }
        //课程名称筛选
        if (isset($course) && !empty($course)) {
            $class_manage_query->andWhere(['cma.course' => $course]);
        }

        $class_manage_data = $class_manage_query->all(Fun::getSiteDb());
        $goods_info_array=[];
        if (empty($class_manage_data)) {
            return ['statusCode' => 0, 'message' => 'error', 'result' => '没有课程'];
        } else {
            foreach ($class_manage_data as $key => $val) {
                $good_data = (new Query())->select('*')->from('{{%goods}}')->where(['id' => $val['goods_id']])->one(Fun::getSiteDb());
                $cate_data = (new Query())->select('*')->from('{{%cate}}')->where(['id' => $good_data['cat_id']])->one();
                $goods_info_array[$val['class_id']] = [
                    'date' => date("Y-m", $val['start_time']),
                    'classify' => $cate_data['name'],
                    'courseName' => isset($val['course_name']) ? $val['course_name'] : '',
                    'courseWeek' => isset($val['course_week']) ? $val['course_week'] : '',
                    'courseBegin' => isset($val['course_begin']) ? $val['course_begin'] : '',
                    'courseEnd' => isset($val['course_end']) ? $val['course_end'] : '',
                    'list' => $this->getOrderlists($val['class_id']),
                ];
            }
            $cate=(new Query())->select('id,name')->from('{{%cate}}')->where(['parent_id'=>0])->all();
            $item=[
                'goods_info_array'=>$goods_info_array,
                'cate'=>$cate
            ];
            return ['statusCode' => 200, 'message' => 'error', 'items' => $item];
        }

    }

    //预约学生列表
    private function getOrderlists($class_id)
    {
        $list = [];
        $goods_ids = (new Query())->select('goods_id')->from('{{%class_manage_goods}}')->where(['class_id' => $class_id])->column(Fun::getSiteDb());
        $student_ids = (new Query())->select('oi.student_id')->from('{{%orders}} o')
            ->leftJoin('{{%orders_items}} oi', 'o.id=oi.orders_id')
            ->where(['in', 'oi.goods_id', $goods_ids])->andWhere(['o.status' => [0, 1], 'o.pay_status' => [0]])->column(Fun::getSiteDb());
        $student = (new Query())->select('*')->from('{{%student}}')->where(['in', 'id', $student_ids])->all();
        if (!empty($student)) {
            foreach ($student as $k => $v) {
                $customer = (new Query())->select('*')->from('{{%customer}}')->where(['id' => $v['customer_id']])->one();
                if ($v['sex'] == 0) { //如果是女的话
                    $sexiconBox = "dmd-female-icon";
                    $sexicon = 'icon-female';
                } else {
                    $sexiconBox = "dmd-male-icon";
                    $sexicon = 'icon-male';
                }
                if (isset($customer['mobile']) && !empty($customer['mobile'])) {
                    $callOrNot = 'dmd-call-box';
                    $call = '拨打';
                } else {
                    $callOrNot = 'dmd-call-not-box';
                    $call = '';
                }
                $list[] = [
                    'img' => isset($v['img']) ? $v['img'] : '../../images/order-count-img-no-have.jpg',
                    'sexiconBox' => $sexiconBox,
                    'sexIcon' => $sexicon,
                    'name' => isset($v['name']) ? $v['name'] : '',
                    'telephone' => isset($customer['mobile']) ? $customer['mobile'] : '暂无联系方式',
                    'callOrNot' => $callOrNot,
                    'call' => $call,
                ];
            }
        }

        return $list;
    }

}